<template>
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<el-card class="box-card">
  <el-row :gutter=20>
  <el-col :span="9">
        <el-input v-model="paramsList.query" clearable @clear="getUsers">
        <el-button slot="append" icon="el-icon-search"  @click="getUsers"></el-button>
    </el-input>
  </el-col>
  <el-col :span="4">
      <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
  </el-col>
</el-row>
<el-table :data="userList" border stripe>
      <el-table-column type="index" ></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change=changeUserState(scope.row)></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
                                                                <!-- 通过插槽scope传递id -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getUserInfo(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
            <el-tooltip  effect="dark" content="操作" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-scissors" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
        </template>

      </el-table-column>
      
    </el-table>
    <!-- 对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="30%"
  >
    <p>当前用户{{userinfo.username}}</p>
    <p>当前角色 {{userinfo.role_name}}</p>
    <p>分配新角色</p>
    <el-select v-model="Selectedvalue" placeholder="请选择">
        <el-option
        v-for="item in allRole"
        :key="item.id"
        :label="item.roleName"
        :value="item.id">
        </el-option>
    </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="paramsList.currentPage"
      :page-sizes="[1, 3, 7]"
      :page-size="paramsList.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paramsList.total">
    </el-pagination>
</el-card>
<!-- 添加用户框 -->
<el-dialog title="用户添加" ref="addForm" :visible.sync="dialogVisible" width="50%" @close="addFormClose">
  <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px">
    <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
    </el-form-item>
    <el-form-item label="电话号码" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>

<!-- 修改用户框 -->
<el-dialog title="用户修改" :visible.sync="changeDialogVisible" width="50%" @close="changeFormClose">
  <el-form :model="editForm" :rules="changeRules" ref="changeForm" label-width="100px">
    <el-form-item label="用户名" >
        <el-input v-model="editForm.username" disabled></el-input>
    </el-form-item>
   
    <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
    </el-form-item>
    <el-form-item label="电话号码" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="changeDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="changeUser">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
export default {
    data() {
         // 验证邮箱
        var checkEmain = (rule, value,callback) => {
            var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if(reg.test(value)){
                return callback()
            }
            callback(new Error('格式错误'))
        };           
          
        // 验证手机
        var checkPhone = (rule, value, callback) =>{
            var reg = /^1[3456789]\d{9}$/
            if(reg.test(value)) return callback()
            callback(new Error('格式错误'))
        }
        return  {
            // 查询到信息
            editForm: {},
            userList: [],
            total: 0,
            paramsList: {
                pagesize:1,
                pagenum: 1,
                query: ''
            },
            dialogVisible: false,
            changeDialogVisible: false,
            // 设置操作按钮对话框
            setRoleDialogVisible: false,
            // 保存当前要被修改的那个对象的信息
            userinfo: {},
            // 保存所有请求到的角色
            allRole: [],
            // 修改用户规则
            changeRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmain, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    {validator: checkPhone, trigger: 'blur' }
                ],
            },
            // 选择框中的选中值
            Selectedvalue: '',

            // 添加用户规则
            addRules: {
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmain, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    {validator: checkPhone, trigger: 'blur' }
                ],
            },
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
           
            
        }
    },
    created() {

        this.getUsers()
    },
    methods: {
        // 点击确定按钮提交分配角色
        async saveRoleInfo() {
            const {data: res} = await this.$http.put(`users/${this.userinfo.id}/role`, {rid: this.Selectedvalue})
            if (res.meta.status !== 200) return this.$message.error('修改失败')
            this.$message.success('修改成功')
            this.Selectedvalue = ''
            this.username = ''
            this.getUsers()
            this.setRoleDialogVisible = false
        },
        // 设置role对话框
        async setRole(userinfo){
            this.userinfo = userinfo
            // 在展开对话框之前获取所有角色列表
            const {data: res} = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取失败')
            this.allRole = res.data
            this.setRoleDialogVisible = true
        },
       addFormClose(){
           this.$refs.addForm.resetFields()
       },
        changeFormClose(){
           this.$refs.changeForm.resetFields()
       },
      
        async getUsers() {
           const {data: res} = await this.$http.get('users', {params: this.paramsList})
           if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
           this.userList = res.data.users
           this.total = res.data.total
           this.currentPage = res.data.pagenum
        },
        handleSizeChange(val){
            this.paramsList.pagesize = val
            this.getUsers()
        },
        handleCurrentChange(val){
            this.paramsList.pagenum = val
            this.getUsers()
        },
        async changeUserState(info) {
            const {data: res} = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
            if (res.meta.status !== 200)
            {
                info.mg_state = !info.mg_state
                return this.$message.error('修改用户状态失败')
            } 
            this.$message.success('修改用户状态成功')
        },
        // 添加用户
        addUser(){
            this.$refs.addForm.validate(async valid => {
                if(!valid) return 
                //添加用户的网络请求
                const {data: res} = await this.$http.post('users', { params: this.editForm })
                if(res.meta.status !== 201) this.$message.error('添加失败')
                this.$message.success('添加成功')
                this.dialogVisible = false
                this.getUsers()

            } )
        },
        // 修改用户时要先获取的用户信息
        async getUserInfo(id) {
            const {data: res} = await this.$http.get('users/'+ id)
            if (res.meta.status !== 200) return this.$message.error('获取失败')
            this.editForm = res.data
            this.changeDialogVisible = true
        },
        // 修改用户信息
        async changeUser() {
             this.$refs.changeForm.validate(async valid => {
            if(!valid) return
            //修改用户的网络请求
            const {data: res} = await this.$http.put('users/'+ this.editForm.id, 
            {email: this.editForm.email,mobile: this.editForm.mobile})
            if (res.meta.status !== 200) return this.$message.error('修改失败')
            this.$message.success('修改成功')
            this.changeDialogVisible = false
            this.getUsers()
        })
     },
     // 删除指定用户
     async delUser(id){
        const confirm = await this.$confirm('是否删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if (confirm !== 'confirm') return this.$message.info('已取消删除')
        // 删除的网络请求
        const {data: res} = await this.$http.delete('users/'+id)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.msg)
        this.$message.info(res.msg)
        this.getUsers()
     }
    
    }
}
</script>

<style  scoped>
</style>